package com.example.api.controller;

import com.example.api.common.core.CommonResult;
import com.example.api.common.redis.ZiDeRedisUtil;
import com.example.api.entity.Category;
import com.example.api.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {

    @Autowired
  private CategoryService categoryService;


    @Autowired
    private ZiDeRedisUtil redisUtil;
    @GetMapping
    public CommonResult getAllCategories() {
        // 1. 定义Redis缓存key
        String redisKey = "categories:all";

        // 2. 先尝试从Redis获取缓存
        List<Category> cachedCategories = redisUtil.getCacheList(redisKey);
        if (cachedCategories != null && !cachedCategories.isEmpty()) {
            // 2.1 如果缓存存在，直接返回缓存数据
            return CommonResult.success("成功从缓存获取分类数据", cachedCategories);
        }

        // 3. 缓存不存在则查询数据库
        List<Category> categories = categoryService.list();

        // 4. 将查询结果存入Redis（设置1小时过期时间）
        if (categories != null && !categories.isEmpty()) {
            redisUtil.setCacheList(redisKey, categories);
            redisUtil.expire(redisKey, 1, TimeUnit.HOURS);
        }

        // 5. 返回统一格式结果
        return CommonResult.success("成功从数据库获取分类数据", categories);
    }
}